<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图-->
    <el-card>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-input v-model="queryInfo.query" placeholder="请输入内容" clearable @clear="getUsersList">
            <el-button @click="getUsersList" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addDialogFormVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--用户列表区-->
      <el-table :data="usersList" style="width: 100%">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <!--<el-table-column prop="create_time" label="日期">
          <template slot-scope="scope" v-text="new Date(scope.row.create_time)"></template>
        </el-table-column>-->
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="changeUserState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="small" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
            <el-button size="small" type="danger" icon="el-icon-delete" @click="deleteUserById(scope.row.id)"></el-button>
            <el-button size="small" type="warning" icon="el-icon-setting" @click="showSetRoleDialog(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页取-->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[2, 5, 10, 20]" :page-size="5" layout="total, sizes, prev, pager, next, jumper" :total="this.total">
      </el-pagination>
    </el-card>
    <!--添加用户的弹出框-->
    <el-dialog title="添加用户" width="500px" @close="addUserDialogClosed" :visible.sync="addDialogFormVisible" >
      <el-form :model="addUserForm" :rules="userFormRules" ref="addUserFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAddUser">确 定</el-button>
      </div>
    </el-dialog>
    <!--修改用户的弹出框-->
    <el-dialog title="修改用户" width="500px" @close="editUserDialogClosed" :visible.sync="editDialogFormVisible" >
      <el-form :model="editUserForm" ref="editUserFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditUser">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="setRoleDialogVisible" width="450px" @close="setRoleDialogClosed">
      <el-row>
        <el-col :span="6">用户名</el-col>
        <el-col :span="18" v-text="currentUser.username"></el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="6">当前角色</el-col>
        <el-col :span="18" v-text="currentUser.role_name"></el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="6">所选角色</el-col>
        <el-col :span="18">
          <el-select v-model="checkRoleId" placeholder="请选择角色">
            <el-option v-for="item in allRoles" :key="item.id + ''" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleByUserId">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      usersList: [],
      total: 0,
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      addDialogFormVisible: false,
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      userFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '用户名的长度在2～10个字',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          {
            min: 6,
            max: 18,
            message: '用户密码的长度在6～18个字',
            trigger: 'blur'
          }
        ]
      },
      editDialogFormVisible: false,
      editUserForm: {
        username: '',
        email: '',
        mobile: ''
      },
      setRoleDialogVisible: false,
      /* 分配角色时当前所选的用户 */
      currentUser: {},
      allRoles: [],
      checkRoleId: ''
    }
  },
  created () {
    this.getUsersList()
    this.getAllRoles()
  },
  methods: {
    async getAllRoles () {
      const { data: res } = await this.$http.get('/roles')
      this.allRoles = res.data
    },
    async getUsersList () {
      const { data: res } = await this.$http.get('/users', {
        params: this.queryInfo
      })
      this.usersList = res.data.users
      this.total = res.data.total
    },
    /* 监听 pagesize 改变的事件 */
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUsersList()
    },
    /* 监听 页码值 改变的事件 */
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUsersList()
    },
    async changeUserState (user) {
      const { data: res } = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
      if (res.meta.status === 200) this.$message.success('修改用户状态成功')
      else {
        this.$message.success('修改用户状态失败')
        user.mg_state = !user.mg_state
      }
    },
    addUserDialogClosed () {
      this.$refs.addUserFormRef.resetFields()
    },
    saveAddUser () {
      this.$refs.addUserFormRef.validate(async vali => {
        if (vali) {
          const { data: res } = await this.$http.post('users', this.addUserForm)
          if (res.meta.status === 201) {
            this.$message.success('添加用户成功')
            this.addDialogFormVisible = false
            this.getUsersList()
          } else this.$message.error('添加用户失败')
        }
      })
    },
    editUserDialogClosed () {
      this.$refs.editUserFormRef.resetFields()
    },
    // 根据ID查询用户信息
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败！')
      }
      this.editUserForm = res.data
      this.editDialogFormVisible = true
    },
    saveEditUser () {
      this.$refs.editUserFormRef.validate(async vali => {
        if (vali) {
          const { data: res } = await this.$http.put('users/' + this.editUserForm.id, {
            email: this.editUserForm.email,
            mobile: this.editUserForm.mobile
          })
          if (res.meta.status === 200) {
            this.$message.success('修改用户成功')
            this.editDialogFormVisible = false
            this.getUsersList()
          } else this.$message.error('修改用户失败')
        }
      })
    },
    async deleteUserById (userId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + userId)
      if (res.meta.status === 200) {
        this.$message.success('删除用户成功')
        this.getUsersList()
      } else this.$message.error('删除用户失败')
    },
    /* 分配角色的弹出款 */
    showSetRoleDialog (user) {
      this.currentUser = user
      this.setRoleDialogVisible = true
    },
    setRoleDialogClosed () {
      this.currentUser = {}
      this.checkRoleId = ''
    },
    async setRoleByUserId () {
      if (this.checkRoleId !== '') {
        const { data: res } = await this.$http.put(`users/${this.currentUser.id}/role`, {
          rid: this.checkRoleId
        })
        if (res.meta.status === 200) {
          this.getUsersList()
          this.setRoleDialogVisible = false
          this.$message.success('分配成功')
        } else this.$message.error('分配失败')
      } else this.$message.error('未选择角色！')
    }
  }
}
</script>
<style lang="less" scoped>
</style>
